package io.jee.caisan.weixin.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayBaseRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.constant.WxPayConstants.TradeType;
import com.github.binarywang.wxpay.service.WxPayService;

import io.jee.alaska.util.Result;
import io.jee.caisan.member.client.service.RemoteBalanceService;
import io.jee.caisan.member.domain.BalanceCaidouInpour;
import io.jee.caisan.weixin.domain.Member;
import io.jee.caisan.weixin.service.MemberService;
import io.jee.caisan.weixin.service.PayService;

@Service
@Transactional
public class PayServiceImpl implements PayService{
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Resource
	private RemoteBalanceService remoteBalanceService;
	
	@Resource
    private WxPayService wxPayService;
	
	@Resource
	private MemberService memberService;

	@Override
	public Result<?> createMpPay(String openid, BigDecimal caidou, BigDecimal money, String notify, String ipAddr) {
		Member member = memberService.findByOpenid(openid);
		if(member == null) {
			return Result.error("用户未绑定，无法创建订单");
		}
		Result<BalanceCaidouInpour> inpourResult = remoteBalanceService.createDifferentInpour(member.getMid(), caidou, money);
		if(!inpourResult.isSuccess()) {
			return Result.error(inpourResult.getMessage());
		}
		BalanceCaidouInpour caidouInpour = inpourResult.getData();
		//BalanceCaidouInpour caidouInpour = remoteBalanceService.getCaidouInpour(inpour.getId());
		try {
			WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
			orderRequest.setDeviceInfo("WEB");
			orderRequest.setBody("彩伞空间-彩豆充值");
			orderRequest.setOutTradeNo(caidouInpour.getId());
			orderRequest.setTotalFee(WxPayBaseRequest.yuanToFee(caidouInpour.getMoney().toString()));
			orderRequest.setSpbillCreateIp(ipAddr);
			orderRequest.setNotifyURL(notify);
			orderRequest.setTradeType(TradeType.JSAPI);
			orderRequest.setOpenid(openid);
			WxPayMpOrderResult payInfo = wxPayService.createOrder(orderRequest);
			Map<String, Object> result = new HashMap<>();
			result.put("payInfo", payInfo);
			result.put("inpourId", caidouInpour.getId());
			return Result.success(result);
		} catch (Exception e) {
			logger.error("微信支付失败！订单号：{},原因:{}", caidouInpour.getId(), e.getMessage());
			e.printStackTrace();
			return Result.error("支付失败，请稍后重试");
		}
	}

	
}
